<?php

namespace adminmatrix\plugins;
use think\exception\HttpException;
use think\facade\Config;

use ReflectionClass;
trait TraitInitRoute
{



    public function route(): void
    {

        $this->app->route->rule('app/:any', function () {
            $path = $this->app->request->pathinfo();
            $path = explode("/" , trim($path , '/'));
            array_shift($path);

            $pluginName = array_shift($path);
            $controller =  array_shift($path) ?? 'Index' ; // 控制器名称
            $controller =   str_replace('.','/',$controller) ?? 'Index';
            $action     =   ucfirst(array_shift($path) ?? 'index'); //  方法名称
            $suffix = Config::get('route.controller_suffix', false) == true ? ucfirst(Config::get('route.controller_layer')) : '';

            // 处理 controller 为驼峰写法
            $controllerParts = explode('/', $controller);
            $lastPartIndex = count($controllerParts) - 1;
            $controllerParts[$lastPartIndex] = ucfirst($controllerParts[$lastPartIndex]);
            $controller = implode('/', $controllerParts);

            // 构建完整命名空间
            $className = "/plugins/{$pluginName}/controller/{$controller}{$suffix}";
            $className = str_replace("/" ,'\\' , $className);

            # 设置 命名空间
            $this->app->setNamespace($className);
            $this->app->setAppPath($this->app->getRootPath() . "plugins" . DS . $pluginName . DS);
            $this->app->setRuntimePath($this->app->getRuntimePath() . "plugins" . DS . $pluginName . DS);
            $this->app->request->setController($controller);
            $this->app->request->setAction($action);

            if (class_exists($className))
            {
                // 加载配置文件
                $configdir = $this->app->getRootPath() . "plugins" . DS . $pluginName . DS . 'config';
                foreach (glob($configdir . "/*.php") as $configfile) {
                    $withoutExtension = pathinfo($configfile, PATHINFO_FILENAME);
                    \think\facade\Config::load($configfile ,'plugin');
                }

                $instance = $this->app->make($className);

                if (method_exists($instance , $action)){
                    \think\facade\Log::info('Calling action: ' . $action);
                    return $this->app->invoke([$instance , $action]);
                }else{
                    throw new HttpException(400 , "{$className}\\{$action} 方法不存在");
                }
            }

            return throw new HttpException(404 , '插件不存在');
        })->middleware(Middleware::class);
    }

}
